package com.gable.exhibition.controller;

import com.alibaba.fastjson.JSON;
import com.gable.common.util.*;
import com.gable.exhibition.model.User;
import com.gable.exhibition.service.InstallService;
import com.gable.exhibition.util.ExceptionUtil;
import com.gable.exhibition.util.MessageUtil;
import com.gable.exhibition.view.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by mj on 2018/1/4.
 * 安装controller
 */
@Controller
@RequestMapping(value="/install")
public class InstallController {

    Logger logger = Logger.getLogger(InstallController.class);

    @Autowired
    InstallService installServer;

    /**
     * 跳转页面
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/page")
    public String page(HttpServletRequest request, HttpServletResponse response){
        return "install/install-page";
    }

    /**
     * 跳转详情
     * @param request
     * @param response
     * @param id
     * @return
     */
    @RequestMapping(value="/info")
    public String info(HttpServletRequest request, HttpServletResponse response, @RequestParam(required = true) Long id){
        return "install/install-info";
    }


    //安装提醒
    @RequestMapping(value="/queryRemind",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil queryRemind(HttpServletRequest request, ParameterView parameterView){
        ReturnResultUtil resultUtil = new ReturnResultUtil(500, MessageUtil.QUERYEXCEPTION);
        try {
            Long userId = parameterView.getUserId();
            UserView sessionUser = CacheData.getSessionUser(userId, 1);
            if(sessionUser == null)
                return new ReturnResultUtil(600,MessageUtil.SESSIONNOTEXITIS);
            Long hospitalId = sessionUser.getHospitalId();
            parameterView.setHospitalId(hospitalId);
            //维修商管理员登录  获取其需要指派工程师的安装单
            if(sessionUser.getTag().intValue() == 1005){
                Long maintainerId = sessionUser.getMaintainerId();
                parameterView.setMaintainerId(maintainerId);
            }
            resultUtil = installServer.queryRemind(parameterView);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultUtil;
    }

    //维修商安装单指派工程师
    @RequestMapping(value="/installDispatch",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil installDispatch(HttpServletRequest request, ParameterView parameterView){
        ReturnResultUtil resultUtil = new ReturnResultUtil(500,MessageUtil.FAILED);
        try {
            Long userId = parameterView.getUserId();
            UserView sessionUser = CacheData.getSessionUser(userId, 1);
            if(sessionUser == null)
                return new ReturnResultUtil(600,MessageUtil.SESSIONNOTEXITIS);
            parameterView.setMaintainerId(sessionUser.getMaintainerId());

            Long installId = parameterView.getInstallId();
            String projectChargePerson = parameterView.getProjectChargePerson();
            String projectChargePersonPhone = parameterView.getProjectChargePersonPhone();
            String estimateInstallDate = parameterView.getEstimateInstallDate();
            if(installId == null)
                return new ReturnResultUtil(500,MessageUtil.INSTALLIDISNULL);
            if(StringUtil.isEmpty(projectChargePerson))
                return new ReturnResultUtil(500,MessageUtil.PROJECTCHARGEPERSON);
            if(StringUtil.isEmpty(projectChargePersonPhone))
                return new ReturnResultUtil(500,MessageUtil.PROJECTCHARGEPERSONPHONE);
            if(StringUtil.isEmpty(estimateInstallDate))
                return new ReturnResultUtil(500,MessageUtil.ESTIMATEINSTALLDATE);
            resultUtil = installServer.installDispatch(parameterView);
        }catch (ExceptionUtil e){
            return new ReturnResultUtil(e.getRet(),e.getMsg(),e.getData());
        }catch (Exception e) {
            e.printStackTrace();
        }
        return resultUtil;
    }

    //安装列表
    @RequestMapping(value="/installList",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil installList(HttpServletRequest request, ParameterView parameterView){
        ReturnResultUtil resultUtil = new ReturnResultUtil(500, MessageUtil.QUERYEXCEPTION);
        try {
            Long userId = parameterView.getUserId();
            UserView sessionUser = CacheData.getSessionUser(userId, 1);
            if(sessionUser == null)
                return new ReturnResultUtil(600,MessageUtil.SESSIONNOTEXITIS);
            int userTag = sessionUser.getTag().intValue();
            //工程师登录，查询到人
            if(userTag == 1004 || userTag == 1006 || userTag == 1009){
                parameterView.setProjectChargePersonId(parameterView.getUserId());
            }
            //管理员登录，查询到角色
            else{
                Long manufacturerId = sessionUser.getManufacturerId();
                Long hospitalId = sessionUser.getHospitalId();
                Long maintainerId = sessionUser.getMaintainerId();
                Long supplierId = sessionUser.getSupplierId();

                parameterView.setHospitalId(hospitalId);
                parameterView.setManufacturerId(manufacturerId);
                parameterView.setMaintainerId(maintainerId);
                parameterView.setSupplierId(supplierId);
            }
            resultUtil = installServer.installList(parameterView);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultUtil;
    }

    //web安装列表
    @RequestMapping(value="/installListForWeb",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil installListForWeb(HttpServletRequest request, ParameterView parameterView){
        ReturnResultUtil resultUtil = new ReturnResultUtil(500, MessageUtil.QUERYEXCEPTION);
        try {
            UserView sessionUser = CacheData.getSessionUser(null, 1);
            if(sessionUser == null)
                return new ReturnResultUtil(600,MessageUtil.SESSIONNOTEXITIS);
            Long hospitalId = sessionUser.getHospitalId();
            if(hospitalId != null)
                parameterView.setHospitalId(hospitalId);
            resultUtil = installServer.installList(parameterView);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultUtil;
    }

    //安装详情
    @RequestMapping(value="/installInfo",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil installInfo(HttpServletRequest request, ParameterView parameterView){
        ReturnResultUtil resultUtil = new ReturnResultUtil(500,MessageUtil.QUERYEXCEPTION);
        try {
            Long installId = parameterView.getInstallId();
            if(installId == null)
                return new ReturnResultUtil(500,MessageUtil.INSTALLIDISNULL);
            resultUtil = installServer.installInfo(parameterView);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultUtil;
    }

    //工程师安装
    @RequestMapping(value="/doInstall",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil doInstall(HttpServletRequest request, InstallView installView){
        ReturnResultUtil resultUtil = new ReturnResultUtil(500,MessageUtil.FAILED);
        try {
            Long installId = installView.getInstallId();
            String sn = installView.getSn();
            String actualInstallDate = installView.getActualInstallDate();
            Long contractDeviceActualSendId = installView.getContractDeviceActualSendId();
            Long userId = installView.getUserId();
            if(installId == null)
                return new ReturnResultUtil(500,MessageUtil.INSTALLIDISNULL);
            if(StringUtil.isEmpty(sn))
                return new ReturnResultUtil(500,MessageUtil.SNISNULL);
            if(StringUtil.isEmpty(actualInstallDate))
                return new ReturnResultUtil(500,MessageUtil.INSTALLIDDATE);
            if(contractDeviceActualSendId == null)
                return new ReturnResultUtil(500,MessageUtil.SENDDEVICEIDISNULL);
            if(userId == null)
                return new ReturnResultUtil(500,MessageUtil.USERIDDOESTNOEXIST);
            resultUtil = installServer.doInstall(installView);
        }catch (ExceptionUtil eu){
            return new ReturnResultUtil(eu.getRet(),eu.getMsg(),eu.getData());
        }catch (Exception e) {
            e.printStackTrace();
        }
        return resultUtil;
    }

    //验收提醒,列表
    @RequestMapping(value="/queryRemindForCheck",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil queryRemindForCheck(HttpServletRequest request, ParameterView parameterView){
        ReturnResultUtil resultUtil = new ReturnResultUtil(500, MessageUtil.QUERYEXCEPTION);
        try {
            Long userId = parameterView.getUserId();
            UserView sessionUser = CacheData.getSessionUser(userId, 1);
            if(sessionUser == null)
                return new ReturnResultUtil(600,MessageUtil.SESSIONNOTEXITIS);
            int userTag = sessionUser.getTag().intValue();
            //工程师登录，查询到人
            if(userTag == 1004 || userTag == 1006 || userTag == 1009){
                parameterView.setProjectChargePersonId(parameterView.getUserId());
            }
            //管理员登录，查询到角色
            else{
                Long manufacturerId = sessionUser.getManufacturerId();
                Long hospitalId = sessionUser.getHospitalId();
                Long maintainerId = sessionUser.getMaintainerId();
                Long supplierId = sessionUser.getSupplierId();

                parameterView.setHospitalId(hospitalId);
                parameterView.setManufacturerId(manufacturerId);
                parameterView.setMaintainerId(maintainerId);
                parameterView.setSupplierId(supplierId);
            }
            resultUtil = installServer.queryRemindForCheck(parameterView);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultUtil;
    }

    //医院验收
    @RequestMapping(value="/doCheck",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil doCheck(HttpServletRequest request, InstallView installView){
        ReturnResultUtil resultUtil = new ReturnResultUtil(500, MessageUtil.QUERYEXCEPTION);
        try {
            Long installId = installView.getInstallId();
            Long userId = installView.getUserId();
            Long contractDeviceActualSendId = installView.getContractDeviceActualSendId();
            String enableTime = installView.getEnableTime();
            Long status = installView.getStatus();

            if(installId == null)
                return new ReturnResultUtil(500,MessageUtil.INSTALLIDISNULL);
            if(userId == null)
                return new ReturnResultUtil(500,MessageUtil.USERIDDOESTNOEXIST);
            if(contractDeviceActualSendId == null)
                return new ReturnResultUtil(500,MessageUtil.SENDDEVICEIDISNULL);
            if(StringUtil.isEmpty(enableTime))
                return new ReturnResultUtil(500,MessageUtil.ENABLETIMEISNULL);
            if(status == null)
                return new ReturnResultUtil(500,MessageUtil.STATUSISNULL);
            resultUtil = installServer.doCheck(installView);
        } catch (ExceptionUtil eu){
            return new ReturnResultUtil(eu.getRet(),eu.getMsg(),eu.getData());
        }catch (Exception e) {
            e.printStackTrace();
        }
        return resultUtil;
    }

    /**
     * 安装信息补全
     * @param request
     * @return
     */
    @RequestMapping(value="/saveInstallData",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil saveInstallData(HttpServletRequest request, InstallView installView){
        ReturnResultUtil resultUtil = new ReturnResultUtil(500,MessageUtil.FAILED);
        try{
            Long userId = installView.getUserId();
            User user = CacheData.getSessionUser(null,2);
//            user.setUserId(1L);
//            user.setUserName("liuxiao");
//            if(user == null)
//                user = CacheData.getSessionUser(userId,1);
            if(user == null)
                return new ReturnResultUtil(600,MessageUtil.SESSIONNOTEXITIS);

            Long installId = installView.getInstallId();
            String sn = installView.getSn();
            String actualInstallDate = installView.getActualInstallDate();
            Long contractDeviceActualSendId = installView.getContractDeviceActualSendId();
            if(installId == null)
                return new ReturnResultUtil(500,MessageUtil.INSTALLIDISNULL);
            if(StringUtil.isEmpty(sn))
                return new ReturnResultUtil(500,MessageUtil.SNISNULL);
            if(StringUtil.isEmpty(actualInstallDate))
                return new ReturnResultUtil(500,MessageUtil.INSTALLIDDATE);
            if(contractDeviceActualSendId == null)
                return new ReturnResultUtil(500,MessageUtil.SENDDEVICEIDISNULL);
            resultUtil = installServer.saveInstallData(installView,user);
        }catch (ExceptionUtil e){
            return new ReturnResultUtil(e.getRet(), e.getMsg(),e.getData());
        }catch (Exception e){
            e.printStackTrace();
        }
        return resultUtil;
    }

    /**
     * 安装确认
     * @param request
     * @param response
     * @param install
     * @return
     */
    @RequestMapping(value="/confirm",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil confirm(HttpServletRequest request, HttpServletResponse response, InstallView install){
        try{
            if(install.getInstallId() == null){
                return new ReturnResultUtil(500,MessageUtil.INSTALLIDISNULL);
            }
            if(install.getStatus() == null){
                return new ReturnResultUtil(500,MessageUtil.STATUSISNULL);
            }
            Long userId = null;
            if(!StringUtil.isEmpty(request.getParameter("userId"))){
                userId = Long.parseLong(request.getParameter("userId"));
            }
            User user = CacheData.getSessionUser(userId,1);
            if(user == null)
                return new ReturnResultUtil(600,MessageUtil.SESSIONNOTEXITIS);
            Long deviceId = install.getDeviceId();
            if(deviceId == null)
                return new ReturnResultUtil(500,MessageUtil.DEVICEIDISNULL);
            return installServer.confirm(install);
        }catch (ExceptionUtil exceptionUtil){
            return new ReturnResultUtil(exceptionUtil.getRet(),exceptionUtil.getMsg(),exceptionUtil.getData());
        }catch (Exception e){
            e.printStackTrace();
            return new ReturnResultUtil(500, MessageUtil.FAILED);
        }
    }
}
